package com.micosco.taskremind.data;


import androidx.room.Ignore;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TaskList {
    private List<Task> INSTANCES;//作业实例
    private List<Task> UNFINISHED;//未完成作业实例
    private Map<Integer, Task> ID_MAP;

    public static final TaskList instance = new TaskList();

    private TaskList() {
        INSTANCES = new ArrayList<>();
        UNFINISHED = new ArrayList<>();
        ID_MAP = new HashMap<>();

        new Thread(() -> {
            TaskList.getInstance().addList(TaskDatabase.getInstance().taskDAO().findAll());
        }).start();
    }

    public void addList(List<Task> allTask) {
        int maxID = 0;

        for (Task task : allTask) {
            INSTANCES.add(task);
            int uid = task.getUID();
            if (uid > maxID) {
                maxID = uid;
            }
            ID_MAP.put(uid, task);
            if (!task.isFinished()) {
                UNFINISHED.add(task);
            }
        }
        Task.setMaxID(maxID);
    }

    @Ignore
    public Task getEarliestDueTask() {
        if (UNFINISHED.size() == 0) {
            return null;
        }

        Task ret = UNFINISHED.get(0);
        for (Task task :
                UNFINISHED) {
            if (task.getDeadline().isBefore(ret.getDeadline())) {
                ret = task;
            }
        }
        return ret;
    }

    /**
     * 返回包含全部未完成作业的不可修改列表
     *
     * @return 包含全部未完成作业的不可修改列表
     */
    public List<Task> getUnfinished() {
        return Collections.unmodifiableList(UNFINISHED);
    }

    /**
     * 返回包含全部作业的不可修改列表
     *
     * @return 包含全部作业的不可修改列表
     */
    public List<Task> getInstances() {
        return Collections.unmodifiableList(INSTANCES);
    }

    public Task findByID(int uID) {
        return ID_MAP.get(uID);
    }

    /**
     * 将作业实例保存到内存列表和本地数据库
     *
     * @param task 需要保存的作业实例
     */
    public void addNewTask(Task task) {
        if (task != null) {
            INSTANCES.add(task);
            if (!task.isFinished()) {
                UNFINISHED.add(task);
            }

            new Thread(() -> {
                while (true) {
                    TaskDatabase db = TaskDatabase.getInstance();
                    if (db != null) {
                        db.taskDAO().add(task);
                        break;
                    }
                }
            }).start();
        }
    }

    public void removeFromUnfinished(int UID) {
        for (int i = 0; i < UNFINISHED.size(); i++) {
            if (UNFINISHED.get(i).getUID() == UID) {
                UNFINISHED.remove(i);
                break;
            }
        }
    }


    public static TaskList getInstance() {
        return instance;
    }

}
